package com.young.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * @Author: young
 * @Date: 2021-12-05 14:57
 * @Description:
 */
public class Dom4jTest {
	@Test
	public void test1() throws DocumentException {
		//创建一个SAXReader输入流，读取xml配置文件，生成document对象
		SAXReader saxReader = new SAXReader();
		
		Document document = saxReader.read("xml/books.xml");
		
		System.out.println(document);
	}
	
	//读取books.xml文件生成BOOK类
	@Test
	public void test2() throws DocumentException {
		//读取books.xml文件
		SAXReader saxReader = new SAXReader();
		//在Junit测试中，相对路径是从模块名开始
		Document document = saxReader.read("xml/books.xml");
		//通过Document对象获取根元素
		Element rootElement = document.getRootElement();
		//通过根元素获取标签对象
		List<Element> books = rootElement.elements("book");
		for (Element book : books) {
			//asXML()把标签对象转换为标签字符串
			Element nameElement = book.element("name");
			//getText()可以获取标签中的文本内容
			String nameText = nameElement.getText();
			//elementText("price")直接获取指定标签名的内容
			String priceText = book.elementText("price");
			String authorText = book.elementText("author");
			String idValue = book.attributeValue("id");
			System.out.println(new Book(idValue,nameText,Double.parseDouble(priceText),authorText));
		}
		//遍历，处理每个book变迁转换为Book类
	}
}
